package com.yunhe.springbootdemo3.controller;


/**
 * 用户的控制层
 */

import com.yunhe.springbootday1.domain.Account;
import com.yunhe.springbootday1.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class AccountController1 {

    private String realPath;


    //业务层方法
    @Autowired
    private AccountService accService;

    /*
    * 注册请求
    * */
    @PostMapping("/account")
    public boolean reg(@RequestBody Account account){

        //调用业务层注册业务
        boolean bl = accService.reg(account);

        return bl;
    }

    /**
     * 验证账号是否存在
     * @param username
     * @return
     */
    @GetMapping("account/username/{uname}")
    public boolean checkUsername(@PathVariable("uname") String username){

        //调用根据用户名进行查询的业务方法
        boolean bl = accService.checkUsername(username);
        return bl;

    }


    @PostMapping("/account/image")
    public String uploadImage(MultipartFile file, HttpServletRequest request) throws IOException {
         realPath = ResourceUtils.getURL("classpath:").getPath();
        //创建出文件
        File file2 = new File(realPath+"static/image");
        file2.mkdirs();

        //获取源文件名
        String oldName = file.getOriginalFilename();

        //创建新文件名
        String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
        //创建新文件对象
        File newFile = new File(file2, newName);
        //输出内容到新文件
        file.transferTo(newFile);

        return newName;

    }


    @DeleteMapping("/account/image/{img}/")
    public String deleteImage(@PathVariable("img") String image){
        System.out.println(image);
        File file = new File(realPath, image);
        file.delete();

        return "删除成功";
    }

    /**
     * 登录请求接收
     */
    @GetMapping("/account/{username}/{password}/")
    public boolean login(@PathVariable("username") String username, @PathVariable("password") String password, HttpSession session){

        //调用登录业务方法
         Account account = accService.login(username,password);

         if(account==null){
             return false;
         }else{

             //登录成功共享用户信息
             session.setAttribute("loginUser",account);

             return true;
         }
    }


    /**
     * 获取用户的登录信息
     * @param session
     * @return
     */
    @GetMapping("/account")
    public Account  loginInfo(HttpSession session){

        Account loginUser =(Account) session.getAttribute("loginUser");

        return loginUser;
    }



}
